<template>
  <div>
    <Modal v-model:visible="visible" title="续订应用" @cancel="onCancel" @ok="onSubmit">
      <div class="md:mt-6">
        <Form
          ref="formRef"
          :label-col="{ span: 5 }"
          :model="formState"
          :rules="rules"
          :wrapper-col="{ span: 12 }"
          name="renewal-form"
        >
          <FormItem label="续订时长" name="duration">
            <InputNumber v-model:value="formState.duration" :min="1" />
            个月
          </FormItem>
        </Form>
      </div>
    </Modal>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, toRaw, watch } from 'vue';
import { Form, FormItem, InputNumber, Modal } from 'ant-design-vue';
import { useUserStore } from '/@/store/modules/user';

interface Values {
  duration: number;
}

const props = defineProps({
  renewalVisible: Boolean,
  appId: String,
});
const emits = defineEmits(['cancelRenewal', 'success']);
const formRef = ref();

const formState = reactive<Values>({
  duration: 1,
});

const rules = {
  duration: [{ required: true, message: '请选择续订时长' }],
};

const visible = ref();

const userStore = useUserStore();

const onSubmit = () => {
  formRef.value
    .validateFields()
    .then(() => {
      let formValues = toRaw(formState);
      let params = {
        tenantCode: userStore.getUserInfo.tenantCode,
        appId: props.appId,
        renewDuration: formValues.duration,
      };
      visible.value = false;
      formRef.value.resetFields();
      emits('success', params);
    })
    .catch(() => {
      emits('cancelRenewal');
    });
};

const onCancel = () => {
  emits('cancelRenewal');
};

watch(
  () => props.renewalVisible,
  (newVal) => {
    visible.value = newVal;
  },
  { immediate: true, deep: true }
);
</script>
